﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;

namespace DusonFramework.Caching.DotNet
{
    public class WebCacheAdapter : ICache
    {
        private System.Web.Caching.Cache _cache;

        /// <summary>
        /// 默认缓存存活期为3600秒(1小时)
        /// </summary>
        protected int _timeOut = 3600;

        public WebCacheAdapter()
        {
            _cache = System.Web.HttpContext.Current.Cache;
        }
        
        public void Add(string key, object value)
        {
            _cache.Add(key, value, null, DateTime.Now.AddSeconds(TimeOut), Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }

        public void AddWithFilesDepend(string key, object value, params string[] files)
        {
            CacheDependency depend = new CacheDependency(files);
            _cache.Add(key, value, depend, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }

        public void AddWithCacheItemsDepend(string key, object value, params string[] dependKey)
        {
            CacheDependency depend = new CacheDependency(null, dependKey);
            _cache.Add(key, value, depend, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
        }

        public void Remove(string key)
        {
            _cache.Remove(key);
        }

        public bool Contains(string key)
        {
            return _cache.Get(key) != null;
        }

        public object Get(string key)
        {
            return _cache.Get(key);
        }

        public int TimeOut
        {
            set { _timeOut = value > 0 ? value : 3600; }
            get { return _timeOut > 0 ? _timeOut : 3600; }
        }
    }
}
